<template>
    <div class="bottom-bar">
        <audio ref="audioRef" :src="playerMusicUrl"></audio>
        <div class="audio">
            <!-- 专辑信息区域 -->
            <div class="audio-img">
                <img alt="专辑封面" :src="playerMusicInfo?.coverImgUrl || coverImgUrl" fit="fill"/>
                <div class="music-info">
                    <div class="music-name-wrap">
                        <span class="music-name">{{ playerMusicInfo?.name || '歌曲名称' }}</span>
                        <Icon name="xihuan" :size="18" />
                    </div>
                    <div class="music-artist">{{ playerMusicInfo?.artist || '演唱人' }}</div>
                </div>
            </div>

            <!-- 播放控制区域 -->
            <div class="audio-play">
                <div class="audio-methods">
                    <Icon :name="playType" :size="18" @click="handlePlayTypeChange" />
                    <Icon name="shangyishou" :size="16" @click="handlePrev" />
                    <Icon
                        :name="isPlaying ? 'zanting' : 'bofang1'"
                        :size="16"
                        @click="handlePlayPause"
                    />
                    <Icon name="xiayishou" :size="16" @click="handleNext" />
                    <Icon name="geciweidianji" :size="16" class="lyric-icon" />
                </div>

                <div class="audio-process">
                    <span class="time-current">{{ formatTime(currentTime) }}</span>
                    <el-progress
                        :percentage="progress"
                        :show-text="false"
                        status="exception"
                        @click="handleProgressClick"
                    />
                    <span class="time-total">{{ formatTime(duration) }}</span>
                </div>
            </div>

            <!-- 右侧控制区域 -->
            <div class="audio-control">
                <div class="quality-btn" @click="handleQualityChange">{{ qualityLabel }}</div>
                <i class="iconfont icon-shengyin volume-icon"></i>
                <i class="iconfont icon-liebiao_o list-icon"></i>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import defaultCoverImg from '@/assets/img/playlist-top.png';
import { usePlaylistStore } from '@/store/playlist';

type PlayType = 'liebiaoxunhuan' | '24gl-repeatOnce2' | 'shunxubofang' | 'suijibofang';
interface ToneQuality { label: string; value: 'standard' | 'higher' | 'exhigh' | 'lossless'; }
interface MusicInfo { coverImgUrl?: string; name?: string; artist?: string; }
const coverImgUrl = ref<string>(defaultCoverImg);
const playlistStore = usePlaylistStore();
const playerMusicUrl = computed(() => playlistStore.playerMusicUrl);
const playerMusicInfo = computed<MusicInfo>(() => playlistStore.playerMusicInfo || {});
const audioRef = ref<HTMLAudioElement | null>(null);
const playTypeList: PlayType[] = ['liebiaoxunhuan', '24gl-repeatOnce2', 'shunxubofang', 'suijibofang'];
const playType = ref<PlayType>('liebiaoxunhuan');
const isPlaying = ref<boolean>(false);
const currentTime = ref<number>(0);
const duration = ref<number>(189);
const progress = ref<number>(0);
const toneQuality: ToneQuality[] = [
    { label: '标准音质', value: 'standard' },
    { label: '较高音质', value: 'higher' },
    { label: '极高音质', value: 'exhigh' },
    { label: '无损音质', value: 'lossless' },
];
const qualityLabel = ref<string>('标准音质');
const qualityValue = ref<'standard' | 'higher' | 'exhigh' | 'lossless'>('standard');

onMounted(() => {
    if (audioRef.value) {
        audioRef.value.addEventListener('timeupdate', handleTimeUpdate);
        audioRef.value.addEventListener('loadedmetadata', handleLoadedMetadata);
        audioRef.value.addEventListener('ended', handleAudioEnded);
    }
});
const handleTimeUpdate = () => {
    if (audioRef.value) {
        currentTime.value = audioRef.value.currentTime;
        progress.value = Math.floor((currentTime.value / duration.value) * 100) || 0;
    }
};
const handleLoadedMetadata = () => {
    if (audioRef.value) duration.value = audioRef.value.duration;
};
const handleAudioEnded = () => handleNext();
const formatTime = (time: number): string => {
    const minutes = Math.floor(time / 60);
    const seconds = Math.floor(time % 60);
    return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
};
const handlePlayPause = () => {
    if (!audioRef.value) return;
    isPlaying.value ? audioRef.value.pause() : audioRef.value.play().catch(err => console.error('播放失败:', err));
    isPlaying.value = !isPlaying.value;
};
const handlePlayTypeChange = () => {
    const currentIndex = playTypeList.indexOf(playType.value);
    playType.value = playTypeList[(currentIndex + 1) % playTypeList.length];
};
const handlePrev = () => console.log('上一首');
const handleNext = () => console.log('下一首');
const handleQualityChange = () => {
    const currentIndex = toneQuality.findIndex(q => q.value === qualityValue.value);
    const nextIndex = (currentIndex + 1) % toneQuality.length;
    qualityValue.value = toneQuality[nextIndex].value;
    qualityLabel.value = toneQuality[nextIndex].label;
};
const handleProgressClick = (e: MouseEvent) => {
    if (!audioRef.value) return;
    const progressBar = e.currentTarget as HTMLElement;
    const rect = progressBar.getBoundingClientRect();
    const clickX = e.clientX - rect.left;
    const percentage = (clickX / rect.width) * 100;
    progress.value = percentage;
    const seekTime = (percentage / 100) * duration.value;
    audioRef.value.currentTime = seekTime;
    currentTime.value = seekTime;
};
watch(playerMusicUrl, (newUrl) => {
    if (newUrl && audioRef.value) {
        audioRef.value.load();
        audioRef.value.play().then(() => isPlaying.value = true).catch(err => {
            console.error('自动播放失败:', err);
            isPlaying.value = false;
        });
    }
});
</script>

<style scoped lang="scss">
// 基础样式（全局通用）
.bottom-bar {
    width: 100%;
    box-sizing: border-box;
    background-color: #fff;
    z-index: 100; 
}

.audio {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 16px;
    box-sizing: border-box;
}

// 专辑信息区域
.audio-img {
    display: flex;
    align-items: center;
    flex-shrink: 0; // 避免被压缩

    img {
        width: 50px;
        height: 50px;
        border-radius: 8px;
        object-fit: cover; // 确保图片不变形
    }

    .music-info {
        margin-left: 12px;
        overflow: hidden; // 避免文字溢出

        .music-name-wrap {
            display: flex;
            align-items: center;
            gap: 8px; // 歌曲名和喜欢图标间距

            .music-name {
                white-space: nowrap; // 强制单行显示
                overflow: hidden;
                text-overflow: ellipsis; // 溢出显示省略号
                max-width: 200px; // 限制最大宽度（PC端）
            }
        }

        .music-artist {
            font-size: 13px;
            color: #666;
            margin-top: 4px;
            white-space: nowrap; // 歌手名单行显示
        }
    }
}

// 播放控制区域
.audio-play {
    display: flex;
    flex-direction: column;
    align-items: center;
    flex-grow: 1; // 占满剩余空间
    margin: 0 16px;

    .audio-methods {
        display: flex;
        justify-content: center;
        align-items: center;

        i {
            cursor: pointer;
            transition: color 0.2s; // hover动画
        }

        i:not(:last-child) {
            margin-right: 20px;
        }

        i:hover {
            color: #f06767;
        }
    }

    .audio-process {
        display: flex;
        align-items: center;
        margin-top: 10px;
        width: 100%; // 占满父容器宽度

        .time-current, .time-total {
            font-size: 12px;
            color: #9999ce;
            width: 40px; // 固定时间显示宽度
            text-align: center;
        }

        .el-progress {
            flex-grow: 1; // 进度条占满剩余空间
            margin: 0 8px;
        }
    }
}

// 右侧控制区域
.audio-control {
    display: flex;
    align-items: center;
    gap: 16px; // 元素间距
    flex-shrink: 0; // 避免被压缩

    .quality-btn {
        border: 1px solid #656565;
        cursor: pointer;
        font-size: 12px;
        padding: 2px 6px;
        border-radius: 4px;
    }

    .iconfont {
        font-size: 24px;
        cursor: pointer;
    }
}

// 响应式适配：平板及以下（768px为分界）
@media (max-width: 768px) {
    .bottom-bar {
        height: 70px; // 移动端高度略小
    }

    // 专辑信息区域调整
    .audio-img {
        img {
            width: 40px; // 封面缩小
            height: 40px;
        }

        .music-info {
            .music-name-wrap .music-name {
                max-width: 120px; // 移动端歌曲名更短
                font-size: 14px;
            }

            .music-artist {
                font-size: 12px;
            }
        }
    }

    // 播放控制区域调整
    .audio-play {
        margin: 0 8px;

        .audio-methods {
            i {
                font-size: 14px !important; // 图标缩小
            }

            i:not(:last-child) {
                margin-right: 12px; // 图标间距缩小
            }

            .lyric-icon {
                display: none; // 移动端隐藏歌词图标（节省空间）
            }
        }

        .audio-process {
            .time-current, .time-total {
                font-size: 10px; // 时间文字缩小
                width: 30px;
            }
        }
    }

    // 右侧控制区域调整
    .audio-control {
        gap: 12px;

        .quality-btn {
            display: none; // 移动端隐藏音质按钮（可移至菜单）
        }

        .iconfont {
            font-size: 20px; // 图标缩小
        }

        .volume-icon {
            display: none; // 移动端隐藏音量图标（可通过手势控制）
        }
    }
}

// 响应式适配：手机小屏（375px以下）
@media (max-width: 375px) {
    .audio {
        padding: 0 8px; // 进一步缩小内边距
    }

    // 专辑信息区域进一步压缩
    .audio-img .music-info {
        .music-name-wrap .music-name {
            max-width: 80px; // 超小屏歌曲名更短
        }
    }

    // 播放控制区域进度条优化
    .audio-play .audio-process .el-progress {
        margin: 0 4px; // 进度条与时间间距缩小
    }
}
</style>